package priv.conceit.sc.hoxton.auth.core.chain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import priv.conceit.sc.hoxton.auth.authority.service.UserService;
import priv.conceit.sc.hoxton.common.entity.auth.authority.pojo.User;
import priv.conceit.sc.hoxton.common.entity.auth.authority.qo.UserLoginQO;
import priv.conceit.sc.hoxton.common.web.exception.WebException;
import priv.conceit.sc.hoxton.common.web.exception.WebExceptionEnum;

import java.util.List;

/**
 * sc-hoxton 工号密码校验
 *
 * @author Conceit
 * @since 1.0.0, 2020/11/4
 */

@Component
public class JobNumberHandler implements UserLoginAccountChainHandler {

	@Autowired
	UserService userService;

	/**
	 * doHandler 执行过滤器链
	 * <p>
	 * 返回
	 * null 执行下一个
	 * User 登陆用户请求信息
	 *
	 * @param userLoginQO
	 * @return User
	 * @author conceit
	 * @date 2020/11/4 17:00
	 */
	@Override
	public User doHandler(UserLoginQO userLoginQO) {
		LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(StrUtil.isNotBlank(userLoginQO.getAccount()),User::getJobNumber,userLoginQO.getAccount());
		List<User> users=userService.list(lambdaQueryWrapper);
		if(CollUtil.isEmpty(users)){
			return null;
		}
		//如果查询是多条记录 throw
		if(users.size()> 2){
			throw new WebException(WebExceptionEnum.EX_USER_ACCOUNT_ERROR);
		}

		return users.get(0);
	}
}
